<?php


namespace common\service;


use common\model\ProjectReviewOptionsModel;
use support\SingletonTrait;

class ProjectReviewOptionsService
{

    // 单例工具
    use SingletonTrait;

    /**
     * 保存
     * @param $data
     * @return array|bool
     * @throws \Exception
     */
    public function save($data)
    {
        if (empty($data["id"])) {
            $res = model(ProjectReviewOptionsModel::class)->addItem($data);
        } else {
            $res = model(ProjectReviewOptionsModel::class)->modifyItem($data);
        }
        return $res;
    }

    /**
     * 多个查找
     * @param $param
     * @return array|false|mixed|string
     * @throws \think\Exception
     */
    public function selectProjectReviewOptions($param)
    {
        $filter = $param["filter"];
        $fields = $param["fields"] ?? "id,name,json,project_id";
        $page = $param["page"] ?? [1, C("database.database_max_select_rows")];
        $projectId = $filter['project_id'];
        $projectReviewOptions = model(ProjectReviewOptionsModel::class)->where($filter)->page(...$page)->field($fields)->select();

        $stepCategoryList = ProjectService::getInstance()->getShowStepCategoryList($projectId);
        $stepCategoryMap = array_column($stepCategoryList, null, 'id');

        //拿取大环节名
        foreach ($projectReviewOptions as &$projectReviewOptionsItem) {
            $optionJson = json_decode($projectReviewOptionsItem["json"], true);
            if (!is_array($optionJson)) {
                $projectReviewOptionsItem["json"] = [];
                continue;
            }

            foreach ($optionJson as $optionJsonIndex => $optionJsonItem) {
                $stepCategoryIds = explode(",", $optionJsonItem["step_category_ids"]);
                $optionJsonItem["name"] = $stepCategoryMap[$stepCategoryIds[0]]["show_name"] ?? "";
                $optionJson[$optionJsonIndex] = $optionJsonItem;
            }
            $projectReviewOptionsItem["json"] = $optionJson;
        }

        return $projectReviewOptions;
    }
}